<template lang="pug">
  .bill-table
    Modal(
      width="820"
      v-model="isShowExportEmployeeModal"
      title="选择员工"
      class-name="vertical-center-modal"
    )
      //- .clearfix.mb-24
      //-   RadioGroup(v-model="differentSecurity" @on-change="securityChange")
      //-     Radio.display-block.mb-5(v-for="(item, index) of commercialArr" :label="item.securityGUID" :key="index") {{item.securityNO}}

      //- .clearfix.mb-24
      //-   Input(v-model="searchIdCardNo" search placeholder="请输入待选员工的身份证号进行搜索，用空格分开" :disabled="!currentSecurityNO" @on-search="getUserList")

      .clearfix
        .ivu-transfer-list.w400.custom-transfer.pull-left
          Row.ivu-transfer-list-header
            Col(span="6") 待选员工
            Col(span="13")
              Button(size="small" @click="handlePrev" :disabled="!(transferData.length > 0 && tableComone.pageIndex > 1)") 上页
              span.pl-5.pr-5.font-12.text-gray-9 {{tableComone.pageIndex}}
              Button(size="small" @click="handleNext" :disabled="!(transferData.length > 0 && tableComone.pageIndex < tableComone.totalPages)") 下页
            Col.text-right(span="5") {{selectTransferData.length}}/{{transferData.length}}

          .ivu-transfer-list-body.pt-4.pb-4
            .clearfix.pall-10
              Input(v-model="employeeNameOrIdCardNo" search placeholder="请输入搜索内容" @on-search="getUserList")
            Checkbox(
              v-if="transferData.length"
              :indeterminate="indeterminateTransferData"
              :value="checkAllTransferData"
              @click.prevent.native="handleCheckAllTransferData"
            ) 全选
            CheckboxGroup(v-model="selectTransferData" @on-change="handleCheckboxChangeTransferData")
              Checkbox.display-block(v-for="(c_item, idx) of transferData" :key="idx" :label="c_item.id") {{c_item.name}}

        .w28.pull-left.ml-10.mr-10.pt-100
          Button.action-icon.mb-10(icon="ios-arrow-forward" :disabled="!(selectTransferData.length > 0)" @click="handleTransfer(selectTransferData, 'transferData', 'targetKeys')")
          Button.action-icon(icon="ios-arrow-back" :disabled="!(selectTargetKeys.length > 0)" @click="handleTransfer(selectTargetKeys, 'targetKeys', 'transferData')")

        .ivu-transfer-list.w320.custom-transfer.pull-left
          Row.ivu-transfer-list-header
            Col(span="18")
              span.pull-left.mr-10 已选员工
              //- Button(size="small" @click="handleShowBatchImportExportEmployeeModal" :disabled="!currentSecurityNO || targetKeys.length === selectArr.length") 导入
            Col.text-right(span="6") {{selectTargetKeys.length}}/{{targetKeys.length}}
          .ivu-transfer-list-body.pt-4.pb-4
            //- .clearfix.pall-10
            //-   Input(v-model="searchBbb" search placeholder="请输入搜索内容" @on-search="getUserList")
            Checkbox(
              v-if="targetKeys.length"
              :indeterminate="indeterminateTargetKeys"
              :value="checkAllTargetKeys"
              @click.prevent.native="handleCheckAllTargetKeys"
            ) 全选
            CheckboxGroup(v-model="selectTargetKeys" @on-change="handleCheckboxChangeTargetKeys")
              Checkbox.display-block(v-for="(c_item, idx) of targetKeys" :key="idx" :label="c_item.id") {{c_item.name}}

        //- .ivu-transfer-list.w240.custom-transfer
        //-   .ivu-transfer-list-header 新增人员
        //-   .ivu-transfer-list-body
        //-     ul.ivu-transfer-list-content
        //-       li.ivu-transfer-list-content-item(v-for="item, index of selectArr" :key="index")
        //-         span.line-h-25 {{item.name}}
        //-         .pull-right
        //-           Icon.action-icon.mr-5(type="ios-arrow-up" @click="handleMoveUp(index)")
        //-           Icon.action-icon(type="ios-arrow-down" @click="handleMoveDown(index)")
      
      .clearfix(v-if="pageType !== 3")
        p.text-center.text-error.mb-30.pt-50 温馨提示：不选择项目的时候为默认导出全部！
        Form.has-rules-item2(ref="formData" :model="formData" :rules="rules" :label-width="110")
          FormItem.form-item(v-for="(item, index) of formItem" :label="item.label" :key="index" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-model="formData[item.model]" :placeholder="item.placeholder" label-in-value @on-change="projectChange" clearable)
                Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="handleSubmit" :loading="!isCanSubmit") 确定

    //- 批量导入商保已选员工
    //- BatchImportExportEmployeeModal(ref="BatchImportExportEmployeeModal" @queryArr="queryTargetKeys")
</template>

<script>
import { MergeBillApi } from '@/api/MergeBill.api.js'
// import { shangbaoReplaceThead } from './../EBtableHead.js'
// import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import { Common } from '@/utils/common.js'
// import BatchImportExportEmployeeModal from './batchImportExportEmployeeModal.vue'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: '',

  props: {
  },

  components: {
    // BatchImportExportEmployeeModal
  },

  data () {
    return {
      modalKey: null,
      isShowExportEmployeeModal: false,
      transferData: [], // 待选员工列表
      selectTransferData: [],
      targetKeys: [], // 已选员工列表
      selectTargetKeys: [],
      selectArr: [],
      isCanSubmit: true,
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 100, // 当前页面展示条数
        totalPages: 0
      },
      formData: {
        project: null,
      },
      formItem: [
        { type: 'select', label: '部分项目：', placeholder: '请选择部分项目', prop: 'project', model: 'project', options: 'BillMergeProject' },
      ],
      rules: {},
      arrListDown: {
        BillMergeProject: [],
      },
      indeterminateTransferData: false,
      checkAllTransferData: false,
      indeterminateTargetKeys: false,
      checkAllTargetKeys: false,
      employeeNameOrIdCardNo: null,
      pageType: null,
      companyIds: null,
      selectedProject: null,
      beginTime: null,
      endTime: null,
    }
  },

  watch: {
  },

  mounted () {
    this.getEnum()
  },

  methods: {
    // 数据字典
    getEnum () {
      let typeName = 'BillMergeProject'
      Common.getSelectValueList(typeName, this.arrListDown)
    },

    ok () {
    },

    cancel () {
      this.isShowExportEmployeeModal = false
    },

    show () {
      this.isShowExportEmployeeModal = true
      this.isCanSubmit = true
      this.transferData = []
      this.targetKeys = []
    },

    // 获取用户列表
    async getUserList () {
      var removeEmployeeIds = this.targetKeys.map(item => {return item.id})
      var params = {
        PageType: this.pageType,
        CompanyIds: this.companyIds,
        EmployeeNameOrIdCardNo: this.employeeNameOrIdCardNo,
        RemoveEmployeeIds: removeEmployeeIds.join(','),
        IsPostBack: true,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
      }
      let res = await MergeBillApi.getUserList(params)
      console.log('获取用户列表: ', res)
      
      if (res.data.success) {
        this.transferData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.totalPages = res.data.totalPages
      }
    },

    // 穿梭框操作
    handleTransfer (arr, currentArr, targetArr) {
      this.indeterminateTransferData = false,
      this.checkAllTransferData = false,
      this.indeterminateTargetKeys = false,
      this.checkAllTargetKeys = false
      
      var tempArr = []
      arr.map(c_item => {
        for (var i = 0; i < this[currentArr].length; i++) {
          if (c_item === this[currentArr][i].id) {
            tempArr.push(this[currentArr][i])
            this[currentArr].splice(i, 1) // 删除当前列表中相应的员工
          }
        }
      })
      this.selectTransferData = []
      this.selectTargetKeys = []
      this[targetArr] = this[targetArr].concat(tempArr) // 所选择的员工加入目标列表
      console.log('❤ targetKeys: ', this.targetKeys)
      this.getUserList()
    },

    // // 交换数组元素
    // swapItems (arr, index1, index2) {
    //   arr[index1] = arr.splice(index2, 1, arr[index1])[0]
    //   return arr
    // },

    // // 上移
    // handleMoveUp (index) {
    //   console.log('上移:', index)
    //   if (index == 0) {
    //     return
    //   }
    //   this.swapItems(this.selectArr, index, index - 1)
    // },

    // // 下移
    // handleMoveDown (index) {
    //   console.log('下移: ', index)
    //   if (index == this.selectArr.length - 1) {
    //     return
    //   }
    //   this.swapItems(this.selectArr, index, index + 1)
    // },

    searchFn (value) {
      console.log('value: ', value)
    },

    projectChange (value) {
      console.log('value: ', value)
      this.selectedProject = value
    },

    // 确定提交
    async handleSubmit () {
      var tempNew = this.targetKeys.map(item => {
        return item.id
      })
      var params = {
        CompanyIds: this.companyIds,
        EmployeeIds: tempNew.join(','),
        Items: this.selectedProject ? [{value: this.selectedProject.value, text: this.selectedProject.label}] : null,
        BeginTime: this.beginTime,
        EndTime: this.endTime,
      }
      let res = this.modalKey == 'summary' ? await MergeBillApi.exportEmployeeSummary(params) : await MergeBillApi.exportEmployeeSummaryDetail(params)
      console.log('确定提交res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.data)
        window.open(baseUrl + res.data.data, '_blank')
        this.isShowExportEmployeeModal = false
        this.$emit('query')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
        this.isCanSubmit = true
      }
    },

    // 批量导入-显示弹窗
    // handleShowBatchImportExportEmployeeModal () {
    //   this.$refs.BatchImportExportEmployeeModal.show()
    //   this.$refs.BatchImportExportEmployeeModal.file = null
    //   this.$refs.BatchImportExportEmployeeModal.errorData.isError = false
    //   this.$refs.BatchImportExportEmployeeModal.currentSecurityNO = this.currentSecurityNO
    //   this.$refs.BatchImportExportEmployeeModal.searchIdCardNo = this.searchIdCardNo
    //   this.$refs.BatchImportExportEmployeeModal.currentCount = this.selectArr.length
    // },

    // 导入已选员工成功后的操作
    // queryTargetKeys (arr) {
    //   // 已选员工列表显示导入后返回的数组去重
    //   this.targetKeys = Common.ToHeavy2(this.targetKeys.concat(arr), 'idCardNo')
    //   // 把去重后的数组的idCardNo放入新数组
    //   var idCardNoArr = []
    //   arr.map(item => {
    //     idCardNoArr.push(item.idCardNo)
    //   })
    //   this.transferData = this.handleMapTransferData(this.transferData, idCardNoArr)
    // },

    // 遍历待选员工列表
    handleMapTransferData (arr, idCardNoArr) {
      var tempArr = []
      arr.map((item, index) => {
        if (idCardNoArr.indexOf(item.idCardNo) === -1) {
          tempArr.push(item)
        }
      })
      return tempArr
    },

    handleCheckboxChangeTransferData (idArr) {
      console.log('🚩idArr: ', idArr)
      var tempIdArr = []
      if (idArr.length === this.transferData.length) {
        this.indeterminateTransferData = false
        this.checkAllTransferData = true
      } else if (idArr.length > 0) {
        this.indeterminateTransferData = true
        this.checkAllTransferData = false
      } else {
        this.indeterminateTransferData = false
        this.checkAllTransferData = false
      }

      this.transferData.map(item => {
        if (idArr.indexOf(item.id) !== -1) {
          tempIdArr.push(item.id) // code数组
        }
      })

      this.selectTransferData = tempIdArr
    },

    handleCheckboxChangeTargetKeys (idArr) {
      console.log('🚩idArr: ', idArr)
      var tempIdArr = []
      if (idArr.length === this.targetKeys.length) {
        this.indeterminateTargetKeys = false
        this.checkAllTargetKeys = true
      } else if (idArr.length > 0) {
        this.indeterminateTargetKeys = true
        this.checkAllTargetKeys = false
      } else {
        this.indeterminateTargetKeys = false
        this.checkAllTargetKeys = false
      }

      this.targetKeys.map(item => {
        if (idArr.indexOf(item.id) !== -1) {
          tempIdArr.push(item.id) // code数组
        }
      })

      this.selectTargetKeys = tempIdArr
    },

    handlePrev () {
      this.tableComone.pageIndex--
      this.getUserList()
    },

    handleNext () {
      this.tableComone.pageIndex++
      this.getUserList()
    },

    // 待选员工全选
    handleCheckAllTransferData () {
      if (this.indeterminateTransferData) {
        this.checkAllTransferData = false;
      } else {
        this.checkAllTransferData = !this.checkAllTransferData;
      }
      this.indeterminateTransferData = false;

      var tempIdArr = []
      if (this.checkAllTransferData) {
        tempIdArr = this.transferData.map(item => {
          return item.id
        })
      } else {
        tempIdArr = [];
      }
      this.selectTransferData = tempIdArr
      console.log('❤ this.selectTransferData: ', this.selectTransferData)
    },

    // 已选员工全选
    handleCheckAllTargetKeys () {
      if (this.indeterminateTargetKeys) {
        this.checkAllTargetKeys = false;
      } else {
        this.checkAllTargetKeys = !this.checkAllTargetKeys;
      }
      this.indeterminateTargetKeys = false;

      var tempIdArr = []
      if (this.checkAllTargetKeys) {
        tempIdArr = this.targetKeys.map(item => {
          return item.id
        })
      } else {
        tempIdArr = [];
      }
      this.selectTargetKeys = tempIdArr
      console.log('❤ this.selectTargetKeys: ', this.selectTargetKeys)
    }
  }
}
</script>

<style lang="less" scope>
.ivu-transfer-list-header{
  height: 42px;
}
.custom-transfer{
  padding-top: 42px;
  height: 250px;
  .ivu-transfer-list-body{
    overflow-y: scroll;
    .ivu-checkbox-wrapper{
      padding: 3px 16px;
      margin: 0;
      clear: both;
      line-height: 25px;
      .ivu-checkbox{
        margin-right: 5px;
      }
    }
  }
  .ivu-transfer-operation{
    .ivu-btn {
      width: 28px;
      height: 25px;
      line-height: 23px;
      text-align: center;
      font-size: 14px;
      padding: 0;
      span{
        display: block;
      }
    }
  }
  .ivu-transfer-list-content-item{
    padding-top: 3px;
    padding-bottom: 3px;
  }
}
.action-icon{
  width: 28px;
  height: 25px;
  line-height: 23px;
  color: #c5c8ce;
  background-color: #f7f7f7;
  border: solid 1px #dcdee2;
  text-align: center;
  font-size: 14px;
  border-radius: 3px;
  transition: all .3s;
  cursor: pointer;
  padding: 0;
  &:hover{
    color: #fff;
    background-color: #2d8cf0;
    border-color: #2d8cf0;
  }
}
</style>
